package com.xiaojie.springboot.provider;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

/**
 * @author xiaojie
 * @version 1.0
 * @description:消息生产者 publisher-confirm-type: correlated
 * #NONE值是禁用发布确认模式，是默认值
 * #CORRELATED值是发布消息成功到交换器后会触发回调方法
 * #SIMPLE值经测试有两种效果，其一效果和CORRELATED值一样会触发回调方法，
 * 其二在发布消息成功后使用rabbitTemplate调用waitForConfirms或waitForConfirmsOrDie方法等待broker节点返回发送结果，
 * 根据返回结果来判定下一步的逻辑，要注意的点是waitForConfirmsOrDie方法如果返回false则会关闭channel，将无法发送消息到broker
 * @date 2021/9/25 22:47
 */
@Component
@Slf4j
public class MsgProvider {
    //定义队列
    private static final String MY_FANOUT_QUEUE = "xiaojie_fanout_queue";
    private static final String MY_DIRECT_QUEUE = "xiaojie_direct_queue";
    private static final String DIRECT_ROUTING_KEY = "msg.send";
    private static final String MY_TOPIC_QUEUE = "xiaojie_topic_queue";
    private static final String TOPIC_ROUTING_KEY = "msg.send";
    //定义fanout交换机
    private static final String MY_FANOUT_EXCHANGE = "xiaojie_fanout_exchange";
    //定义direct交换机
    private static final String MY_DIRECT_EXCHANGE = "xiaojie_direct_exchange";
    //定义topics交换机
    private static final String MY_TOPICS_EXCHANGE = "xiaojie_topics_exchange";
    @Autowired
    private AmqpTemplate amqpTemplate;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    public String sendMSg(Integer type, String msg) {
        try {
            if (1 == type) {
                //发送到fanout
                rabbitTemplate.convertAndSend(MY_FANOUT_QUEUE, "fanout" + msg);
            } else if (2 == type) {
                //第一个参数交换机，第二个参数，路由键，第三个参数，消息
                rabbitTemplate.convertAndSend(MY_DIRECT_EXCHANGE, DIRECT_ROUTING_KEY, "direct" + msg);
            } else if (3 == type) {
                rabbitTemplate.convertAndSend(MY_TOPICS_EXCHANGE, TOPIC_ROUTING_KEY, "topic" + msg);
            }
            return "success";
        } catch (AmqpException e) {
            e.printStackTrace();
        }
        return "error";
    }
}
